
//
//  NSObject+GetURLContent.m
//  Unity-iPhone
//
//  Created by Dengzeyu on 14/12/29.
//
//

#import "GetURLContent.h"
#import "KindsView.h"
#import "jingtai.h"
#import "Model.h"
#import "M_shop.h"
#import "MHFileTool.h"
#import "M_content.h"
@implementation GetURLContent
@synthesize data;
-(NSString *)getkindID:(NSString *) lujing {
    lujing= [lujing stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:lujing];
    
    NSString * str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    str =[[str componentsSeparatedByString:@"&"] objectAtIndex:0];
    return str;
}
-(NSString *)getisdianzan:(NSString *)lujing
{
    lujing= [lujing stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:lujing];
    
    NSString * str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    str =[[str componentsSeparatedByString:@"&"] objectAtIndex:0];
    return str;
}
-(NSString *)getzannum:(NSString *)lujing
{
    lujing= [lujing stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:lujing];
    
    NSString * str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    str =[[str componentsSeparatedByString:@"&"] objectAtIndex:0];
    return str;

}
-(void)Load:(NSString *)lujing andshopview:(ShopViewController *) shopview
{
    kinds = SHOP;
    self.shopview = shopview;
    lujing= [lujing stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:lujing];

    NSString * str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    [self parastring:str andShopKind:self.shopview.kind andKind:@"shop"];
//    //创建一个请求
//    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
//
//    //发送请求（使用代理的方式）
//    NSURLConnection *connt=[[NSURLConnection alloc] initWithRequest:request delegate:self ];
//    [connt start];
}
-(void)parastring:(NSString *)str andShopKind:(NSString *)kindname andKind:(NSString *)kind
{
    NSFileManager * fm =[[NSFileManager alloc] init];
    BOOL isdir = FALSE;
    BOOL isexist =[fm fileExistsAtPath:[MHFileTool getLocalFilePath:@"local"] isDirectory:&isdir];
    if(!(isexist && isdir))
    {
         BOOL bCreateDir = [fm createDirectoryAtPath:[MHFileTool getLocalFilePath:@"local"] withIntermediateDirectories:YES attributes:nil error:nil];
        if(bCreateDir)
        {
            NSLog(@"创建成功！");
        }
        else
        {
            NSLog(@"创建失败");
        }
    }
    NSString * datafromweb= str;
    [jingtai sharedSingleton].dataforweb = datafromweb;
    NSString* temp=str;
    
    if ([temp hasSuffix:@"SuccessfromDZYkind"] && ![temp isEqualToString:@"SuccessfromDZYkind"])
    {
        
        [temp writeToFile:[MHFileTool getLocalFilePath:@"/local/DZYkind.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        NSArray *datas=[datafromweb componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
            [self parseJsonDatakind:[temp dataUsingEncoding:NSUTF8StringEncoding]];
            
        }
        [[jingtai sharedSingleton].kindview loadscroll];
        // jingtai.sharedSingleton.Maincontroll.Topic.pics=jingtai.sharedSingleton.Maincontroll.tempArray;
        //[jingtai.sharedSingleton.Maincontroll.Topic upDate];
        //NSDictionary * a=jingtai.sharedSingleton.Version;
        //[jingtai.sharedSingleton.kameng shuaxin];
        //[jingtai.sharedSingleton.Maincontroll refresh];
        
    }
    else if([temp hasSuffix:@"SuccessfromShare"])
    {
           [temp writeToFile:[MHFileTool getLocalFilePath:@"/local/Share.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        NSArray *datas=[temp componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
            
        }
        //NSDictionary * a=jingtai.sharedSingleton.Version;
        // [jingtai.sharedSingleton.Maincontroll refresh];
        //[jingtai.sharedSingleton.kameng shuaxin];
    }
    else if ([temp hasSuffix:@"SuccessfromDZY"] && ![temp isEqualToString:@"SuccessfromDZY"])
    {
        BOOL isdirshop = FALSE;
        NSString * lujing =[MHFileTool getLocalFilePath:[NSString stringWithFormat: @"local/%@",self.shopview.kind]];
        BOOL isexistshop =[fm fileExistsAtPath:lujing isDirectory:&isdirshop];
        if(!(isdirshop && isexistshop))
        {
            BOOL bCreateDir = [fm createDirectoryAtPath:lujing withIntermediateDirectories:YES attributes:nil error:nil];
            if(bCreateDir)
            {
                NSLog(@"创建shopdir成功！");
            }
            else
            {
                NSLog(@"创建shopdir失败");
            }
        }
        NSString * lujingshop =[MHFileTool getLocalFilePath:[NSString stringWithFormat: @"local/%@/DZY.txt",self.shopview.kind]];
        [temp writeToFile:lujingshop atomically:YES encoding:NSUTF8StringEncoding error:nil];

        NSArray *datas=[temp componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
            [self parseJsonDatashop:[temp dataUsingEncoding:NSUTF8StringEncoding]];
        }
      
        
       
        
    }
    else if ([temp hasSuffix:@"SuccessfromDZYversion"]&& ![temp isEqualToString:@"SuccessfromDZYversion"])
    {
        [temp writeToFile:[MHFileTool getLocalFilePath:@"/local/DZYversion.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];

        NSArray *datas=[temp componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
            [self parseJsonVersion:[temp dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    else if ([temp hasSuffix:@"SuccessfromDZYcontent"]&& ![temp isEqualToString:@"SuccessfromDZYcontent"])
    {
        BOOL isdirkind = FALSE;
        BOOL isdirshop = FALSE;
        NSString * lujing =[MHFileTool getLocalFilePath:[NSString stringWithFormat: @"local/%@",self.kindname]];
        NSString * shopPath =[MHFileTool getLocalFilePath:[NSString stringWithFormat: @"local/%@/%@",self.kindname,self.shopname]];
        BOOL isexistkind =[fm fileExistsAtPath:lujing isDirectory:&isdirkind];
        BOOL isexistshop;
        if(!(isdirkind &&isexistkind))
        {
            BOOL bCreateDir = [fm createDirectoryAtPath:lujing withIntermediateDirectories:YES attributes:nil error:nil];
            if(bCreateDir)
            {
                NSLog(@"创建kinddir成功！");
               BOOL bCreateDirshop =[fm createDirectoryAtPath:shopPath withIntermediateDirectories:YES attributes:nil error:nil];
                if(bCreateDirshop)
                {
                    NSLog(@"shop 创建成功！");
                }
                else
                {
                    NSLog(@"shop 创建失败！");
                }
            }
            else
            {
                NSLog(@"创建kinddir失败");
            }

        }
        isexistshop =[fm fileExistsAtPath:shopPath isDirectory:&isexistshop];
        if(!(isdirshop && isexistshop))
        {
            BOOL bCreateDir = [fm createDirectoryAtPath:shopPath withIntermediateDirectories:YES attributes:nil error:nil];
            if(bCreateDir)
            {
                NSLog(@"shop 创建成功！");
            }
            else
            {
                NSLog(@"shop 创建失败！");
            }

        }
        [temp writeToFile:shopPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        NSArray *datas=[temp componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
            [self parseJsonContent:[temp dataUsingEncoding:NSUTF8StringEncoding]];
        }
        [[jingtai sharedSingleton].contentview loadscroll:NO];
    }
    else//网络异常加载本地数据！
    {
       if(self.shopview!=nil)
       {
            BOOL isdirshop = FALSE;
           NSString * lujing =[MHFileTool getLocalFilePath:[NSString stringWithFormat: @"local/%@",self.shopview.kind]];
           BOOL isexistshop =[fm fileExistsAtPath:lujing isDirectory:&isdirshop];
           if(!(isdirshop && isexistshop))
           {
               BOOL bCreateDir = [fm createDirectoryAtPath:lujing withIntermediateDirectories:YES attributes:nil error:nil];
               if(bCreateDir)
               {
                   NSLog(@"创建shopdir成功！");
               }
               else
               {
                   NSLog(@"创建shopdir失败");
               }
           }
           NSString * lujingshop =[MHFileTool getLocalFilePath:[NSString stringWithFormat: @"local/%@/DZY.txt",self.shopview.kind]];
           if([MHFileTool isExistsFileInDoc:[NSString stringWithFormat: @"local/%@/DZY.txt",self.shopview.kind]])
           {
               [self parastring:[NSString stringWithContentsOfFile:lujingshop encoding:NSUTF8StringEncoding error:nil] andShopKind:kindname andKind:@"shop"];
           }
           else{
               NSLog(@"网络异常，本地shop数据加载失败！");
           }
       }
    else if([kind isEqualToString:@"version"])
        {
            NSString * versionPath =[MHFileTool getLocalFilePath:@"/local/DZYversion.txt"];
            if([fm fileExistsAtPath:versionPath])
            {
                [self parastring:[NSString stringWithContentsOfFile:versionPath encoding:NSUTF8StringEncoding error:nil] andShopKind:nil andKind:@"version"];
            }
            else
            {
                 NSLog(@"网络异常，本地version数据加载失败！");
            }
        }
        else if([kind isEqualToString:@"kind"])
        {
            NSString * versionPath =[MHFileTool getLocalFilePath:@"/local/DZYkind.txt"];
            if([fm fileExistsAtPath:versionPath])
            {
                [self parastring:[NSString stringWithContentsOfFile:versionPath encoding:NSUTF8StringEncoding error:nil] andShopKind:nil andKind:@"kind"];
            }
            else
            {
                NSLog(@"网络异常，本地kind数据加载失败！");
            }

        }
        else if([kind isEqualToString:@"content"])
        {
            NSString * lujingcontent =[MHFileTool getLocalFilePath:[NSString stringWithFormat: @"local/%@/%@/DZY.txt",self.kindname,self.shopname]];
            if([fm fileExistsAtPath:lujingcontent])
            {
                [self parastring:[NSString stringWithContentsOfFile:lujingcontent encoding:NSUTF8StringEncoding error:nil] andShopKind:nil andKind:@"content"];
            }
            else
            {
                NSLog(@"网络异常，本地kind数据加载失败！");
            }
            
        }
    }
    
    NSLog(@"下载完毕");
 
}
//kind 当前加载的类型
-(void)Load:(NSString *)lujing andkind:(NSString *)kind

{
    kinds = KIND;
    lujing= [lujing stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:lujing];
    
    NSString * str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    [self parastring:str andShopKind:nil andKind:kind];
}

#pragma mark- NSURLConnectionDataDelegate代理方法
/*
 *当接收到服务器的响应（连通了服务器）时会调用
 */
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{    //初化data
    self.data=[NSMutableData alloc];
    NSLog(@"要下载文件大小为 %lld",response.expectedContentLength);
   
}

/*
 *当接收到服务器的数据时会调用（可能会被调用多次，每次只传递部分数据）
 */
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1
{
    
    [self.data appendData:data1];
    //一点一点接收数据。
        //NSLog(@"接收到服务器的数据！---%f",(((float)(now.length)/(float)(jingtai.sharedSingleton.Size)))*100);
    // NSString * a =[NSString stringWithFormat:@"%f",(((float)(now.length)/(float)(jingtai.sharedSingleton.Size)))*100];
    //UnitySendMessage("Unitysendmessage", "downloadbaifenbi", [a UTF8String]);
}

/*
 *当服务器的数据加载完毕时就会调用
 */
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
        NSString * datafromweb= [[NSString alloc] initWithData:self.data  encoding:NSUTF8StringEncoding];
    [jingtai sharedSingleton].dataforweb = datafromweb;
    NSString* temp=[[NSString alloc] initWithData:self.data  encoding:NSUTF8StringEncoding];

     if ([temp hasSuffix:@"SuccessfromDZYkind"] && ![temp isEqualToString:@"SuccessfromDZYkind"])
    {

        
        NSArray *datas=[datafromweb componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
            [self parseJsonDatakind:[temp dataUsingEncoding:NSUTF8StringEncoding]];
            
        }
        [[jingtai sharedSingleton].kindview loadscroll];
       // jingtai.sharedSingleton.Maincontroll.Topic.pics=jingtai.sharedSingleton.Maincontroll.tempArray;
        //[jingtai.sharedSingleton.Maincontroll.Topic upDate];
        //NSDictionary * a=jingtai.sharedSingleton.Version;
        //[jingtai.sharedSingleton.kameng shuaxin];
        //[jingtai.sharedSingleton.Maincontroll refresh];

    }
    else if([temp hasSuffix:@"SuccessfromShare"])
    {
        NSArray *datas=[temp componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
    
        }
        //NSDictionary * a=jingtai.sharedSingleton.Version;
        // [jingtai.sharedSingleton.Maincontroll refresh];
        //[jingtai.sharedSingleton.kameng shuaxin];
    }
    else if ([temp hasSuffix:@"SuccessfromDZY"] && ![temp isEqualToString:@"SuccessfromDZY"])
    {
        NSArray *datas=[temp componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
            [self parseJsonDatashop:[temp dataUsingEncoding:NSUTF8StringEncoding]];
        }
        [self.shopview loadscroll];

    }
        else
        {
            NSLog(@"Wrong! aboutdownloadcontent");
        }
    
    NSLog(@"下载完毕");
   
}
-(void)parseJsonString:(NSString *)strings
{
    NSString* temp;
    if([strings hasSuffix:@"SuccessfromDZY"])
    {
        NSArray *datas=[strings componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
            [self parseJsonDatashop:[temp dataUsingEncoding:NSUTF8StringEncoding]];
        }
        //NSDictionary * a=jingtai.sharedSingleton.Version;
        //[jingtai.sharedSingleton.Maincontroll refresh];
        //[jingtai.sharedSingleton.kameng shuaxin];
    }
    else if ([temp hasSuffix:@"SuccessfromDZYkind"] && ![temp isEqualToString:@"SuccessfromDZYkind"])
    {
        NSArray *datas=[jingtai.sharedSingleton.dataforweb componentsSeparatedByString:@"&"];
        for (int i=0; i<[datas count]-1; i++) {
            temp=[datas objectAtIndex:i];
            [self parseJsonDatakind:[temp dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
        //NSDictionary * a=jingtai.sharedSingleton.Version;
        //[jingtai.sharedSingleton.kameng shuaxin];
        //[jingtai.sharedSingleton.Maincontroll refresh];
        
    }
    
    else
    {
        NSLog(@"Wrong! aboutdownloadcontent");
    }
    
    NSLog(@"下载完毕");

}
-(void) parseJsonVersion:(NSData *)data1
{
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&error];
    if (json == nil) {
        NSLog(@"json parse failed \r\n");
        return;
    }
    else
    {
        [jingtai sharedSingleton].kindversion = [json objectForKey:@"Kindversion"];
        [jingtai sharedSingleton].shopversion = [json objectForKey:@"Shopversion"];
        [jingtai sharedSingleton].contentversion = [json objectForKey:@"Contentversion"];
    }
    
   
    
    
}
-(void) parseJsonContent:(NSData *)data1
{
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&error];
    if (json == nil) {
        NSLog(@"json parse failed \r\n");
        return;
    }
    else
    {
        M_content * content = [[M_content alloc] init];
        content.name = [json objectForKey:@"Name"];
        content.Version =[json objectForKey:@"Version"];
        content.Lujing = [json objectForKey:@"Lujing"];
        content.Zhuangtai = [json objectForKey:@"Zhuangtai"];
        content.Sort = [json objectForKey:@"Sort"];
        content.Icon = [json objectForKey:@"Icon"];
        content.shopname = self.shopname;
        content.kindname = self.kindname;
        content.kind =2;
        [[jingtai sharedSingleton].URLappList addObject:content];
    }
    
    
    
    
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog([error description]);//网络数据访问失败。
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"网络信息加载失败！！" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];
    //[jingtai.sharedSingleton.kameng shuaxin];
   // [jingtai.sharedSingleton.Maincontroll refresh];
}
-(void) parseJsonData:(NSData *)data1
{
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&error];
    if (json == nil) {
        NSLog(@"json parse failed \r\n");
        return;
    }
    NSString *name = [json objectForKey:@"Name"];
    NSString *Version=[json objectForKey:@"Version"];
    NSString *Lujing=[json objectForKey:@"Lujing"];
    NSString *Displayname=[json objectForKey:@"Displayname"];
    NSString *Description=[json objectForKey:@"Description"];


}
-(void) parseJsonDatashop:(NSData *)data1
{
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&error];
    if (json == nil) {
        NSLog(@"json parse failed \r\n");
        return;
    }
    Model * temp = [[M_shop alloc] init];
    M_shop * shop =(M_shop *)temp;
    shop.Icon = [json objectForKey:@"Icon"];
    shop.name = [json objectForKey:@"Name"];
    shop.kind = 1;
    shop.zan = [json objectForKey:@"Zan"];
    shop.comid = [json objectForKey:@"Comid"];
    [self.shopview.appList addObject:shop];
    // [jingtai.sharedSingleton.Maincontroll.tempArray addObject:[NSDictionary dictionaryWithObjects:@[[json objectForKey:@"URL"],[json objectForKey:@"Title"],@NO,[UIImage imageNamed:@"error.jpg"],[json objectForKey:@"Wangzhi"]] forKeys:@[@"pic",@"title",@"isLoc",@"placeholderImage",@"URL"]]];
    
}
-(void) parseJsonDatakind:(NSData *)data1
{
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&error];
    if (json == nil) {
        NSLog(@"json parse failed \r\n");
        return;
    }
    Model * temp = [[Model alloc] init];
    temp.Icon = [json objectForKey:@"Icon"];
    temp.name = [json objectForKey:@"Name"];
    temp.kind = 0;
    [[jingtai sharedSingleton].kindview.appList addObject:temp];
   // [jingtai.sharedSingleton.Maincontroll.tempArray addObject:[NSDictionary dictionaryWithObjects:@[[json objectForKey:@"URL"],[json objectForKey:@"Title"],@NO,[UIImage imageNamed:@"error.jpg"],[json objectForKey:@"Wangzhi"]] forKeys:@[@"pic",@"title",@"isLoc",@"placeholderImage",@"URL"]]];

}
+(void)timerFireMethod:(NSTimer*)theTimer
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}
+(void)showAlert:(NSString *) title andText:(NSString *) text

{
    
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:title message:text delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:3.0f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:NO];
    
    [promptAlert show];
}
@end
